import { UserRepository } from '../repositories/user.repository.js'
import type { CreateUserInput, UpdateUserInput } from '@shared/types'

export class UserService {
  private userRepository: UserRepository

  constructor() {
    this.userRepository = new UserRepository()
  }

  /**
   * 获取用户列表
   */
  async getUsers(options: { limit?: number; offset?: number; sex?: string }) {
    const where = options.sex ? { sex: options.sex } : {}

    return await this.userRepository.findMany({
      limit: options.limit,
      offset: options.offset,
      where
    })
  }

  /**
   * 根据 UID 获取用户
   */
  async getUserByUid(uid: string) {
    const user = await this.userRepository.findByUid(uid)
    if (!user) {
      throw new Error(`用户 UID ${uid} 未找到`)
    }

    // 不返回密码
    const { password, ...userWithoutPassword } = user
    return userWithoutPassword
  }

  /**
   * 创建用户
   */
  async createUser(input: CreateUserInput) {
    // 如果包含 email，检查是否已存在
    if (input.email) {
      const existingUser = await this.userRepository.findByEmail(input.email)
      if (existingUser) {
        throw new Error('该邮箱已被注册')
      }
    }

    return await this.userRepository.create({
      email: input.email,
      nickname: input.nickname,
      age: input.age ?? null,
      sex: input.sex ?? null
    })
  }

  /**
   * 更新用户
   */
  async updateUser(uid: string, input: UpdateUserInput) {
    // 先检查用户是否存在
    const existingUser = await this.userRepository.findByUid(uid)
    if (!existingUser) {
      throw new Error(`用户 UID ${uid} 未找到`)
    }

    return await this.userRepository.update(uid, input)
  }

  /**
   * 删除用户
   */
  async deleteUser(uid: string) {
    // 先检查用户是否存在
    const existingUser = await this.userRepository.findByUid(uid)
    if (!existingUser) {
      throw new Error(`用户 UID ${uid} 未找到`)
    }

    return await this.userRepository.delete(uid)
  }
}
